// 认证相关 Mock 数据

import type { LoginRequest, LoginResponse, RegisterRequest, RegisterResponse } from '@/types/user';
import type { ApiResponse } from '@/types/api';

// 模拟用户数据库
const mockUsers = [
  {
    id: 'user_001',
    username: 'test_user',
    password: '123456',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  }
];

// 模拟登录延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

/**
 * Mock 登录接口
 */
export const mockLogin = async (data: LoginRequest): Promise<ApiResponse<LoginResponse>> => {
  await delay(800); // 模拟网络延迟

  const user = mockUsers.find(
    u => u.username === data.username && u.password === data.password
  );

  if (!user) {
    return {
      code: 401,
      data: null as any,
      message: '用户名或密码错误'
    };
  }

  const token = `mock_token_${Date.now()}_${Math.random().toString(36).substring(2)}`;
  
  return {
    code: 200,
    data: {
      token,
      user: {
        id: user.id,
        username: user.username,
        avatar: user.avatar
      }
    },
    message: '登录成功'
  };
};

/**
 * Mock 注册接口
 */
export const mockRegister = async (data: RegisterRequest): Promise<ApiResponse<RegisterResponse>> => {
  await delay(800);

  // 检查用户名是否已存在
  const existingUser = mockUsers.find(u => u.username === data.username);
  
  if (existingUser) {
    return {
      code: 400,
      data: null as any,
      message: '用户名已存在'
    };
  }

  // 创建新用户
  const newUser = {
    id: `user_${Date.now()}`,
    username: data.username,
    password: data.password,
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
  };

  mockUsers.push(newUser);

  return {
    code: 200,
    data: {
      userId: newUser.id
    },
    message: '注册成功'
  };
};

/**
 * Mock 登出接口
 */
export const mockLogout = async (): Promise<ApiResponse<null>> => {
  await delay(300);
  
  return {
    code: 200,
    data: null,
    message: '登出成功'
  };
};